/*************************************************************************
 * File Name:    Balanced_Binary_Tree.cc
 * Author:       zero91
 * Mail:         jianzhang9102@gmail.com
 * Created Time: 2013/11/4 15:03:21
 * 
 * Description:  
 |------------------------------------------------------------------------
 | Problem: Balanced Binary Tree
 | Given a binary tree, determine if it is height-balanced.
 |
 | For this problem, a height-balanced binary tree is defined as a binary tree
 | in which the depth of the two subtrees of every node never differ by more than 1.
 |------------------------------------------------------------------------
 ************************************************************************/

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>

using namespace std;

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode *root)
    {
        if (root == NULL) return true;
        
        return dfs(root, 0);
    }
    
    int dfs(TreeNode *root, int depth)
    {
        if (root == NULL) return depth;
        
        int left_depth = dfs(root->left, depth + 1);
        int right_depth = dfs(root->right, depth + 1);
        
        if (left_depth == 0 || right_depth == 0) return 0;
        
        if (abs(left_depth - right_depth) <= 1) {
            return max(left_depth, right_depth);
        }
        return 0;
    }
};

